﻿using Essensoft.Paylink.Alipay;
using Essensoft.Paylink.Alipay.Notify;
using Essensoft.Paylink.WeChatPay;
using Essensoft.Paylink.WeChatPay.V3;
using Essensoft.Paylink.WeChatPay.V3.Notify;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using StudyCompanion.Core.API;
using StudyCompanion.IServices;

namespace StudyCompanion.WebApi.Controllers;

/// <summary>
///     回调通知
/// </summary>
[AllowAnonymous]
[ApiController]
[Route("api/[controller]")]
public class NotifyController : ApiController
{
    private readonly IAlipayNotifyClient _alipayNotifyClient;
    private readonly IOptions<AlipayOptions> _alipayOptions;
    private readonly ILogger<NotifyController> _logger;
    private readonly IOrderService _orderService;
    private readonly IWeChatPayNotifyClient _weChatPayNotifyClient;
    private readonly IOptions<WeChatPayOptions> _weChatPayOptions;

    public NotifyController(ILogger<NotifyController> logger, 
        IWeChatPayNotifyClient weChatPayNotifyClient, 
        IOptions<WeChatPayOptions> weChatPayOptions, 
        IAlipayNotifyClient alipayNotifyClient, 
        IOptions<AlipayOptions> alipayOptions, 
        IOrderService orderService)
    {
        _logger = logger;
        _weChatPayNotifyClient = weChatPayNotifyClient;
        _weChatPayOptions = weChatPayOptions;
        _alipayNotifyClient = alipayNotifyClient;
        _alipayOptions = alipayOptions;
        _orderService = orderService;
    }

    /// <summary>
    ///     微信支付回调
    /// </summary>
    /// <returns></returns>
    [HttpPost("WeChatPay")]
    public async Task<IActionResult> WeChatPayNotice()
    {
        try
        {
            var notify =
                await _weChatPayNotifyClient.ExecuteAsync<WeChatPayTransactionsNotify>(Request,
                    _weChatPayOptions.Value);
            _logger.LogInformation("支付结果通知 => OutTradeNo: " + notify.OutTradeNo);
            await _orderService.WechatPayNotify(notify);
            return WeChatPayNotifyResult.Success;
        }
        catch (WeChatPayException ex)
        {
            _logger.LogWarning("出现异常: " + ex.Message);
            return WeChatPayNotifyResult.Failure;
        }
    }

    /// <summary>
    ///     支付宝扫码支付回调地址
    /// </summary>
    /// <returns></returns>
    [HttpPost("AliPay")]
    public async Task<IActionResult> AliPayNotice()
    {
        try
        {
            var notify =
                await _alipayNotifyClient.CertificateExecuteAsync<AlipayTradePrecreateNotify>(Request,
                    _alipayOptions.Value);
            await _orderService.AliPayNotify(notify);
            return AlipayNotifyResult.Success;
        }
        catch (Exception ex)
        {
            _logger.LogWarning("出现异常: " + ex.Message);
            return AlipayNotifyResult.Failure;
        }
    }
}